package org.ccay.ws;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.ccay.core.exception.ExceptionHandler;
import org.ccay.core.exception.FaultVO;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;

import sun.security.util.SecurityConstants;

/**
 * Rest 错误处理器
 * 
 * 
 * @since 2012-2-2
 */
@SuppressWarnings("rawtypes")
@Provider
public class WebServiceExceptionMapper implements ExceptionMapper {

	ILogger log = CcayLoggerFactory.getLogger(WebServiceExceptionMapper.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
	 */
	public Response toResponse(Throwable ex) {
		// 先记录到日志里
		ex = ExceptionHandler.digException(ex);
		ExceptionHandler.logException(ex);

		FaultVO fault = ExceptionHandler.getFriendlyFault(ex);
		
		//TODO 权限
		/*
		IPersonalPermissionService personalPermissionService = Ccay
				.getContext().getBean("personalPermissionService",
						IPersonalPermissionService.class);

		// begin add by zwx304259 安全问题无权限用户不返回堆栈信息
		if (!personalPermissionService.hasPermission(
				SecurityConstants.SECURITY_RESOURCE_TYPE_SERVICE,
				"Logs.Search", "SearchLogInfo")) {
			fault.setStackTrace("");
		}*/
		

		// end add by zwx304259 无权限用户不返回堆栈信息

		ResponseBuilder rb = genResponseBuilder(fault);
		rb.type("application/json;charset=UTF-8");
		rb.entity(fault);
		// rb.language(Locale.SIMPLIFIED_CHINESE);
		Response r = rb.build();
		return r;
	}

	/**
	 * 获取ResponseBuilder
	 * 
	 * @param fault
	 * @return
	 */
	private ResponseBuilder genResponseBuilder(FaultVO fault) {

		if (fault.getHttpCode() != 0) {
			return Response.status(fault.getHttpCode());
		}
		return Response.status(Response.Status.INTERNAL_SERVER_ERROR);
	}
}
